package main

import (
	"fmt"
	"log"
	"time"

	"github.com/kataras/iris"
)

const pageSize int = 30

type historyData struct {
	Time time.Time
	Name string
	Room string
	Msg  string
}

//showHistory /history/{roomName:string}/{pageNumber:long}
func (site1 *Site) showHistory(ctx iris.Context) {
	room := ctx.Params().GetString("roomName")
	var cond1 = ""
	if room != "all" {
		cond1 = "where room=?"
	}
	page, err := ctx.Params().GetInt("pageNumber")
	if err != nil {
		page = 0
	}
LOOP1:
	sql1 := fmt.Sprintf("select time,name,room,msg from history %s order by id desc limit %d offset %d;",
		cond1, pageSize, page*pageSize)
	var res []historyData
	db := site1.Db
	_, err = db.Query(&res, sql1, room)
	if err != nil {
		log.Println(err)
		ctx.WriteString(err.Error())
		return
	}
	lastp := page - 1
	if lastp < 0 {
		lastp = 0
	}
	lenRes := len(res)
	if lenRes == 0 && page > 0 {
		page--
		goto LOOP1
	}
	reverseRes := make([]*historyData, lenRes)
	for i := 0; i < lenRes; i++ {
		reverseRes[i] = &res[lenRes-i-1]
	}
	data := iris.Map{"Prefix": site1.Prefix,
		"Rooms":    site1.Rooms,
		"Room":     room,
		"Records":  reverseRes,
		"Page":     page,
		"LastPage": lastp,
		"NextPage": page + 1}
	ctx.ViewData("", data)
	ctx.View("history.html")
}

//findHistory /history/{roomName:string}/s
//search sql: "select * from history where strpos(msg,'go')>0 or strpos(name,'go')>0;"
func (site1 *Site) findHistory(ctx iris.Context) {
	room := ctx.Params().GetString("roomName")
	var cond1, cond2 string
	if room != "all" {
		cond1 = "room=?0"
	} else {
		cond1 = "true"
	}
	w := ctx.URLParam("w")
	if w != "" {
		cond2 = "(strpos(msg,?1)>0 or strpos(name,?1)>0)"
	} else {
		cond2 = "true"
	}
	page, _ := ctx.URLParamInt("p")
	if page == -1 {
		page = 0
	}

LOOP1:
	sql1 := fmt.Sprintf("select time,name,room,msg from history where %s and %s order by id desc limit %d offset %d;",
		cond1, cond2, pageSize, page*pageSize)
	var res []historyData
	db := site1.Db
	_, err := db.Query(&res, sql1, room, w)
	if err != nil {
		log.Println(err)
		ctx.WriteString(err.Error())
		return
	}
	lastp := page - 1
	if lastp < 0 {
		lastp = 0
	}
	lenRes := len(res)
	if lenRes == 0 && page > 0 {
		page--
		goto LOOP1
	}
	reverseRes := make([]*historyData, lenRes)
	for i := 0; i < lenRes; i++ {
		reverseRes[i] = &res[lenRes-i-1]
	}
	data := iris.Map{"Prefix": site1.Prefix,
		"Rooms":    site1.Rooms,
		"Room":     room,
		"Records":  reverseRes,
		"Page":     page,
		"LastPage": lastp,
		"NextPage": page + 1,
		"Word":     w}
	ctx.ViewData("", data)
	ctx.View("search.html")
}
